using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

[RequireComponent(typeof(NetworkIdentity))]
public class ObjectsSpawner : NetworkBehaviour
{
	public bool SpawnOnStart = true;

	public float timeSpawn = 120f;

	public GameObject[] Obj;

	public int ObjMax = 3;

	public Vector3 Offset = new Vector3(0f, 0.1f, 0f);

	public bool PlaceOnGround = true;

	private float timeTemp;

	private List<GameObject> itemList = new List<GameObject>();

	private int ObjectsNumber;

	private void Start()
	{
		if (SpawnOnStart)
		{
			Spawn();
		}
	}

	private void Spawn()
	{
		if (!base.isServer)
		{
			return;
		}
		ObjectExistCheck();
		if (ObjectsNumber >= ObjMax)
		{
			return;
		}
		if (Obj.Length > 0)
		{
			GameObject gameObject = Obj[Random.Range(0, Obj.Length)];
			Vector3 position = base.transform.position;
			Vector3 localScale = base.transform.localScale;
			int min = -(int)(localScale.x / 2f);
			Vector3 localScale2 = base.transform.localScale;
			float x = Random.Range(min, (int)(localScale2.x / 2f));
			Vector3 localScale3 = base.transform.localScale;
			int min2 = (int)((0f - localScale3.z) / 2f);
			Vector3 localScale4 = base.transform.localScale;
			Vector3 position2 = DetectGround(position + new Vector3(x, 0f, Random.Range(min2, (int)(localScale4.z / 2f))));
			GameObject gameObject2 = UnitZ.gameNetwork.RequestSpawnObject(gameObject.gameObject, position2, Quaternion.identity);
			if ((bool)gameObject2)
			{
				itemList.Add(gameObject2);
			}
		}
		timeTemp = Time.time;
	}

	private void ObjectExistCheck()
	{
		ObjectsNumber = 0;
		foreach (GameObject item in itemList)
		{
			if (item != null)
			{
				ObjectsNumber++;
			}
		}
	}

	private void Update()
	{
		if (base.isServer && Time.time > timeTemp + timeSpawn)
		{
			Spawn();
		}
	}

	private void OnDrawGizmos()
	{
		Gizmos.color = Color.blue;
		Gizmos.DrawSphere(base.transform.position, 0.2f);
		Gizmos.DrawWireCube(base.transform.position, base.transform.localScale);
	}

	private Vector3 DetectGround(Vector3 position)
	{
		if (PlaceOnGround && Physics.Raycast(position, -Vector3.up, out RaycastHit hitInfo, 1000f))
		{
			return hitInfo.point + Offset;
		}
		return position;
	}

	private void UNetVersion()
	{
	}

	public override bool OnSerialize(NetworkWriter writer, bool forceAll)
	{
		bool result = default(bool);
		return result;
	}

	public override void OnDeserialize(NetworkReader reader, bool initialState)
	{
	}
}
